//
//  ProgressBankView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2019/1/3.
//  Copyright © 2019年 DUONIU_MAC. All rights reserved.
//

import UIKit

@objc protocol ProgressBankViewDelegate {
    @objc optional func selectBank(urlStr:String) //选择银行
    @objc optional func changeFrame(count:Int) //修改坐标
}

class ProgressBankView: UIView {
    
    var title : String! {
        didSet{
            if title == progressQuery {
                urlStr = webUrl + "/mobile/schedule"
            }else if title == creditCardActivation {
                urlStr = webUrl + "/mobile/activation"
            }
            
            getData()
        }
    }
    
    fileprivate var urlStr = "" //链接
    
    weak var delegate : ProgressBankViewDelegate?
    
    fileprivate let cellId = "bankCell"
    fileprivate var dataArray = [[String:String]]() //银行信息
    var popularBankArray = [[String:String]]() //热门银行信息
    
    fileprivate var collectionView : UICollectionView!

    init() {
        super.init(frame: .zero)
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = .init(width: ScreenW/3, height: RATIO_H(maxNum: 60))
        
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.clear
        collectionView.showsVerticalScrollIndicator = false
        collectionView.isScrollEnabled = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(ProgressCell.self, forCellWithReuseIdentifier: cellId)
        self.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
    }
    
    //MARK: 获取数据
    fileprivate func getData() {
        
        KMTool.requestGetData(URLString: self.urlStr, parameters: nil, success: { (data) in
            
            var elements:[String]!
            var attributes:[String]!
            var keys:[String]!
            
            switch self.title {
            case progressInquiry://进度查询
                elements = ["//div[@class='all_div_bottom']/a","//div[@class='all_div_bottom']/a/img","//div[@class='all_div_bottom']/a/span"]
                attributes = ["href","src","text"]
                keys = ["bank_href","img_src","bank_text"]
            case creditCardActivation://信用卡激活
                elements = ["//div[@class='all_div_bottom']/a","//div[@class='all_div_bottom']/a/img","//div[@class='all_div_bottom']/a/span"]
                attributes = ["href","src","text"]
                keys = ["bank_href","img_src","bank_text"]
            default:
                break
            }
            
            //热门银行通知
        NotificationCenter.default.post(name: .popularBankPush, object: nil, userInfo: ["data":data])
            
            let array = KMTool.htmlToModel(data: data, elements: elements, attributes: attributes, keys: keys)
            
            for model in array {
                if model["bank_text"] != "" {
                    self.dataArray.append(model)
                }
            }
            
            self.delegate?.changeFrame!(count: self.dataArray.count)
            
            self.collectionView.reloadData()
            
        }) {
            
        }
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension ProgressBankView : UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? ProgressCell
        cell?.titleLabel.text = dataArray[indexPath.row]["bank_text"]
        cell?.imageView.image = UIImage.imageWithName(KMTool.selectBankImage(bankName: dataArray[indexPath.row]["bank_text"] ?? ""))
        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var urlString = dataArray[indexPath.row]["bank_href"]
        
        if urlString == "https://c.pingan.com/apply/mobile/modules/queryApp/index.html#queryf" || urlString == "https://creditcard.pingan.com.cn/financing/newpublic/modules/new_activation/index.html#index" {
            urlString = "https://bank-static.pingan.com.cn/ca/ccBooking/ccBookingHtml/query/index.html"
        }
        
        if urlString == "https://kefu.creditcard.cmbc.com.cn/wdxykindex.shtml#dingWeiAllByHSY" {
            
            urlString = "https://creditcard.cmbc.com.cn/home/cn/web/business/account/progress/index.shtml"
        }
        
        self.delegate?.selectBank!(urlStr: urlString ?? "")
    }
}
